<?php

namespace App\Http\Controllers\api;

use App\Constant\Enum;
use App\Models\Adreward;
use App\Models\Commission;
use App\Models\Group;
use App\Models\GroupApply;
use App\Models\ReturnMoneyLog;
use App\Models\Transaction;
use App\Models\User;
use App\Services\Wallet\UserWalletService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

class AuthController extends BaseController
{
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['openid', 'password']);

        $user = User::query()->where(['openid' => $credentials['openid']])->first();
        if (!$user) {
            return $this->error('Invalid credentials', [
                'error' => 'Invalid credentials'
            ], HttpResponse::HTTP_UNAUTHORIZED);
        } else {
            $user->logined();
        }
        $token = auth('jwt')->login($user);

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userinfo()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $userinfo = $this->getUserInfo($user);

        return $this->success($userinfo->toArray());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    public function groupInfo(Request $request)
    {

        $user = auth('jwt')->user();
        $group_apply = GroupApply::where('user_id', $user->id)->where('status', 'approved')->where('is_pay', 1)->first();

        if ($group_apply && strtotime("+ " . $group_apply->days . " days", strtotime($group_apply->created_at)) >= Carbon::today()->endOfDay()->timestamp) {

            $limit = intval($group_apply->price / $group_apply->days / $group_apply->amount);
            $count = ReturnMoneyLog::where('uid', $user->id)->where('status', 1)->count();
            $data = [
                "limit_day" => Carbon::createFromTimestamp(strtotime("+ " . $group_apply->days . " days", strtotime($group_apply->created_at)))->format('Y-m-d'),
                "money" => $group_apply->amount,
                "num" => $limit,
                "amount" => $group_apply->price,
                "total_amount" => round($count * $group_apply->amount)
            ];

            return $this->success($data);
        } else {

            $data = [
                "amount" => 0,
                "total_amount" => 0
            ];
            return $this->success($data);
        }
    }




    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        $user = auth('jwt')->setToken($token)->user();
        if ($user->getAttribute('status') != Enum::STATUS_ENABLED) {
            return $this->error('用户封禁中，请联系管理员！');
        }

        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('jwt')->factory()->getTTL() * 60,
            'user' => $this->getUserInfo($user),
        ]);
    }

    private function getUserInfo(User $user)
    {
        $parent = $user->parent()->first();
        $user->parent_uuid = $parent->uuid ?? '';
        $user->is_group = $user->is_group_leader;
        // 今日
        $todayStart = Carbon::today();
        $todayEnd = Carbon::tomorrow();
        // 昨日
        $yesterdayStart = Carbon::yesterday();
        $yesterdayEnd = Carbon::today();
        $one = 0;
        $two = 0;
        $three = 0;
        $ids = [];
        $twoids = [];
        //是否是高级团长//is_advanced_group
        if ($user->is_advanced_group) {

            $ids = User::where('parent_id', $user->id)->pluck('id')->toArray();
            if (!empty($ids)) {
                $one = count($ids);
                $twoids = User::whereIn('parent_id', $ids)->pluck('id')->toArray();
                if (!empty($twoids)) {
                    $two = count($twoids);
                    $three = User::whereIn('parent_id', $twoids)->count();
                }
            }
            $user->fans = $one + $two + $three;
            $sumids = array_merge($ids, $twoids, [$user->id]);
            $user->today_fans = User::whereIn('parent_id', $sumids)
                ->whereBetween('registered_at', [$todayStart, $todayEnd])
                ->count();
            $user->yester_fans = User::whereIn('parent_id', $sumids)
                ->whereBetween('registered_at', [$yesterdayStart, $yesterdayEnd])
                ->count();

        } else {

            $ids = User::where('parent_id', $user->id)->pluck('id')->toArray();
            if (!empty($ids)) {
                $one = count($ids);
                $two = User::whereIn('parent_id', $ids)->count();
            }
            $user->fans = $one + $two;
            $sumids = array_merge($ids, [$user->id]);
            $user->today_fans = User::whereIn('parent_id', $sumids)
                ->whereBetween('registered_at', [$todayStart, $todayEnd])
                ->count();
            $user->yester_fans = User::whereIn('parent_id', $sumids)
                ->whereBetween('registered_at', [$yesterdayStart, $yesterdayEnd])
                ->count();
        }
        //红包收益
        $ad = Adreward::query()->where('user_id', $user->id)->whereBetween('received_at', [$todayStart, $todayEnd])->sum('amount');
        //团队收益+//师徒收益+//任务xzb_task，xianwan_task，qianliang_task，duomi_task，shangbanwan_task，qie_task
        $cn = Commission::query()->whereIn('source', ['group_cash', 'direct_invite', 'xzb_task', 'xianwan_task', 'qianliang_task', 'duomi_task', 'shangbanwan_task', 'qie_task'])->whereBetween('created_at', [$todayStart, $todayEnd])->sum('user_money');
        $user->current_yield = $ad + $cn;
        $user->withdrawable_coins = UserWalletService::getWithdrawableCoins($user);
        $user->today_coins = UserWalletService::getTodayCoins($user);
        $user->package_info = Transaction::where('user_id', $user->id)->where('status', 'pending')->orderBy('id', 'asc')->value('package_info');

        return $user;
    }
}
